/**
 * Created by arvin on 2017/4/22 0022.
 */


(function ($) {
    'use strict';

    // TOOLS DEFINITION
    // ======================

    var cachedWidth = null;

    // it only does '%s', and return '' when arguments are undefined
    var sprintf = function (str) {
        var args = arguments,
            flag = true,
            i = 1;

        str = str.replace(/%s/g, function () {
            var arg = args[i++];

            if (typeof arg === 'undefined') {
                flag = false;
                return '';
            }
            return arg;
        });
        return flag ? str : '';
    };


    // Ldap CLASS DEFINITION
    // ======================

    var Ldap = function (el, options) {
        this.options = options;
        this.$el = $(el);

        if(this.$el[0].multiple&&this.options.multiple ===undefined){
            this.options.multiple = true;
        }


        this.init();
    };

    Ldap.DEFAULTS = {
        btn:{
           // float:'left',
            float:'right',
            iconClass:'fa fa-user'
        },
        autoLength:5,
        insideCss:true,
        onFocus:function(obj){
            obj.focus();
        },
        onClearAll:function(obj){
            obj.clearAll();
        },
        onRemoveItem:function(obj,index){
            obj.removeItem(index);
        },
        onAddItem:function(obj,datas){
            obj.addItem(datas);
        },
        onInsert:function(obj,index,data){
            obj.insert(index,data);
        },
        onLoad:function(obj,value){
            obj.load(value);
        },
        onDataRefresh:function(obj){
            obj.dataRefresh();
        }

    };
    Ldap.EVENTS = {
        'focus.bs.object':'onFocus',
        'clearAll.bs.object':'onClearAll',
        'removeItem.bs.object':'onRemoveItem',
        'addItem.bs.object':'onAddItem',
        'dataRefresh.bs.object':'onDataRefresh',
        'load.bs.object':'onLoad',
        'all.bs.object': 'onAll'
    };

    Ldap.prototype.init = function () {
       // console.log('init');
        this.initContainer();
        this.initCss();
        this.initData();
        this.initBtn();
        this.initAjax();
    };
    Ldap.prototype.initContainer = function () {
        this.$container = $([
            '<div class="ldap-component">',
                '<div class="group">',
                '<span class="iconBtn"><i class="userIcon"></i><i class="loadIcon fa fa-spinner"></i></span>',
                '<ul class="selectItems"></ul>',
                '</div>',
                '<div class="dropdown">',
                '<ul class="selecting"></ul>',
                '</div>',
            '</div>'
        ].join(''));
        this.$container.insertAfter(this.$el);
        this.$input = $('<input class="input" type="text"/>')
        this.$inputgroup = this.$container.find(".group");
        this.$inputbtn = this.$container.find(".iconBtn");
        this.$selectItems = this.$container.find(".selectItems");
        this.$dropdown = this.$container.find(".dropdown");
        this.$selecting = this.$container.find(".selecting");
        this.$inputbtn.find('.userIcon').addClass(this.options.btn.iconClass);
        this.$el.attr('type','hidden');
        if(this.options.btn.float=='right'){

           this.$inputgroup
               .addClass('right')
               .prepend(this.$input);
        }else{
            this.$inputgroup.addClass('left')
                .append(this.$input);
        }
        this.$inputgroup.append(this.$el);
        this.$dropdown.width(this.$container.width())




    };
    Ldap.prototype.initBtn = function (){
        var obj = this;
        this.$inputbtn.off('click').on('click',function(){
            obj.addItem(['username'])
        });

        this.$input.off('keyup mouseup').on('keyup mouseup',function(){
             var value = $.trim($(this).val());
            if(this.status==='loading'){
                 return;
            }
            if(value.length<obj.options.autoLength){
                return;
            }
            if(obj.timer2){
                clearTimeout(obj.timer2);
                obj.timer2=null;
            }
            obj.timer2=setTimeout(function(){
                obj.trigger('load',obj,value);
                obj.timer2=null;
            },500);

        });
        this.$dropdown.off('mouseenter ').on('mouseenter',function(){
            if(obj.timer){
                clearTimeout(obj.timer);
                obj.timer=null;
            }


        })
            .off('mouseleave  ').on('mouseleave ',function(){
            obj.autoHideDown();
        })
    };
    Ldap.prototype.initCss = function () {
        if(1){
            return;
        }
        var sheet =  document.styleSheets[0];
        sheet.addRule('.ldap-component', '');
        sheet.addRule('.ldap-component .group',
            ['position: relative',
              'box-sizing: border-box'
            ].join(';'));
        sheet.addRule('.ldap-component .group.left',
            [ 'padding-left:50px'
            ].join(';'));
        sheet.addRule('.ldap-component .group.right',
            [
               'padding-right:50px'
            ].join(';'));
        sheet.addRule('.ldap-component .left.input',
            ['display:inline-block',
              'width:100%',
              'box-sizing: border-box'
            ].join(';'));
        sheet.addRule('.ldap-component .right .input',
            ['display:inline-block',
                'width:100%',
                'box-sizing: border-box'
            ].join(';'));
        sheet.addRule('.ldap-component .input',
            ['display:inline-block',
                'width:100%',
                'box-sizing: border-box'
            ].join(';'));
        sheet.addRule('.ldap-component .iconBtn',
            ['display:inline-block',
                'width:50px',
                'background-color:red',
                'color:#fff;'
            ].join(';')
        );


    };
    Ldap.prototype.initData = function (options){
        var list =this.options.items;
        if(list&&list.length){
            this.selectItems = list;
            this.trigger('dataRefresh',this);
        }
    };
    Ldap.prototype.initAjax = function (){

    };
    Ldap.prototype.focus = function () {
        this.$input.focus();
    };
    Ldap.prototype.clearAll = function () {
        this.selectItems = [];
        this.trigger('dataRefresh',this);
    };
    Ldap.prototype.removeItem = function (index) {
        if(index >= this.selectItems.length){
            return;
        }
        var _bIlist = this.selectItems.slice(0,index),
            _aIlist = this.selectItems.slice(index+1);
        this.selectItems = _bIlist.concat(_aIlist);
        this.trigger('dataRefresh',this);
    };
    Ldap.prototype.addItem = function (datas) {
        if(this.options.multiple){
            this.selectItems = this.selectItems.concat(datas);
        }else{
            this.selectItems = datas;
        }

        this.trigger('dataRefresh',this);
    };
    Ldap.prototype.insert = function (index,data) {
        if(index >= this.selectItems.length){
            return;
        }else if(index ==this.selectItems.length-1){
            this.selectItems =  this.selectItems.concat([data]);
            this.trigger('dataRefresh',this);
            return;
        }



        var _bIlist = this.selectItems.slice(0,index),
            _aIlist = this.selectItems.slice(index);
        this.selectItems = _bIlist.concat([data]).concat(_aIlist);
        this.trigger('dataRefresh',this);
    };
    Ldap.prototype.load = function (value) {
        //set start
        this.status='loading';
        this.$selecting.html('');
        this.statusChange();
        (function(obj){
            setTimeout(function(){
                obj.status='loadend';
                var datas=['guojing g000001','qiaofeng q000002','weixiaobao w000003'];
                obj.refreshSelectingItems(datas);
                obj.statusChange();
            },2000);
        })(this,value);
        this.trigger('dataRefresh',this);
    };
    Ldap.prototype.refreshSelectingItems = function (datas) {
        var $ul =  this.$selecting, obj=this;
        $ul.html('');
        $(datas).each(function(i,item){
            var $li=$('<li></li>');
            $li.text(item)
                .data('value',item)
                .off('click')
                .on('click',function(){
                var value=$(this).data('value');
                    obj.addItem([value]);
                    obj.$input.val('');
                    obj.hideDropDown();
            })
            $ul.append($li);
        });
    }
    Ldap.prototype.statusChange = function () {
      if(this.status==='loading'){
          this.$input.attr('readonly','readonly');
          this.$inputbtn.addClass('loading');
          this.showDropDown();
      } else{
          this.$input.removeAttr('readonly');
          this.$inputbtn.removeClass('loading');

      }
    };
    Ldap.prototype.hideDropDown = function () {
        this.$dropdown.addClass('none');
        clearTimeout(this.timer);
        this.timer=null;
    };
    Ldap.prototype.showDropDown = function () {
        var obj=this;
        obj.timer=null;
        obj.$dropdown.removeClass('none');
        obj.autoHideDown();

    }
    Ldap.prototype.autoHideDown = function (){
        var obj=this;
        obj.timer = setTimeout(function(){
                obj.$dropdown.addClass('none');
            }
            ,5000);
    }
    Ldap.prototype.dataRefresh = function () {
        var list = this.selectItems,
             $ul=this.$selectItems,
            obj = this;
        $ul.html('')
        $(list).each(function(i,item){
            var $li =$('<li></li>');
            $li.append('<span class="username">'+item+'</span>');
            $li.append('<i class="fa fa-times"></i>');
            $li.find('i').data('index',i).off('click').on('click',function(e){
                obj.removeItem($(e.target).data('index'));
            });

            $ul.append($li);
        });
        (function(ob){
            setTimeout(function(){
                var childNodes = obj.$selectItems[0].childNodes;
                var width=0;
                for(var i=0;i<childNodes.length;i++){
                    console.log($(childNodes[i]).width());
                    width += $(childNodes[i]).width() + 16;
                }
                //obj.$selectItems.width(width);
                obj.$input.css({
                    paddingLeft:width+3
                })
            },200);
        })(obj,$ul);

        this.$el.val(list.join());
    };
    Ldap.prototype.trigger = function (name) {
        var args = Array.prototype.slice.call(arguments, 1);

        name += '.bs.object';
        this.options[Ldap.EVENTS[name]].apply(this.options, args);
        this.$el.trigger($.Event(name), args);


    };

    // Ldap PLUGIN DEFINITION
    // =======================

    var allowedMethods = [
        'setItems','getItems',
        'refresh',
        'destroy'
  ];

    $.fn.Ldap = function (option) {
        var value,
            args = Array.prototype.slice.call(arguments, 1);

        this.each(function () {
            var $this = $(this),
                data = $this.data('Ldap.myObject'),
                options = $.extend({}, Ldap.DEFAULTS, $this.data(),
                    typeof option === 'object' && option);

            if (typeof option === 'string') {
                if ($.inArray(option, allowedMethods) < 0) {
                    throw new Error("Unknown method: " + option);
                }

                if (!data) {
                    return;
                }

                value = data[option].apply(data, args);

                if (option === 'destroy') {
                    $this.removeData('Ldap.myObject');
                }
            }

            if (!data) {
                $this.data('Ldap.myObject', (data = new Ldap(this, options)));
            }
        });

        return typeof value === 'undefined' ? this : value;
    };

    $.fn.Ldap.Constructor = Ldap;
    $.fn.Ldap.defaults = Ldap.DEFAULTS;
    $.fn.Ldap.columnDefaults = Ldap.COLUMN_DEFAULTS;
    $.fn.Ldap.methods = allowedMethods;
    $.fn.Ldap.utils = {
        sprintf: sprintf

    };

    // Ldap INIT
    // =======================

    $(function () {
        $('[data-toggle="tree"]').Ldap();
    });
})(jQuery);
